package com.okilo.online.app.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.okilo.online.app.R
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.configs.OkiloConfigs.addParams
import com.okilo.online.app.databinding.OkiloActFeedbackBinding
import com.okilo.online.app.databinding.OkiloActFeedbackQuestionTypeItemBinding
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.apt.OkiloOnItemChildClickListener
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.imgcovert.ImageConvert
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.apt.OkiloFeedbackImageApt
import com.okilo.online.app.pet.OkiloFeedbackPet
import com.okilo.online.app.pet.OkiloUploadPet
import com.okilo.online.app.pet.view.IOkiloFeedback
import com.okilo.online.app.pet.view.IOkiloUpload
import com.okilo.online.app.weight.font.OkiloRbtMediumEditText
import org.json.JSONObject
import java.io.File

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/27 13:45
 * @Annotation：意见反馈
 */
class OkiloFeedbackAct: OkiloComAct(), IOkiloUpload, IOkiloFeedback {
    private var _binding: OkiloActFeedbackBinding? = null
    private val typeTitleList = arrayListOf(
        R.string.okilo_feedback_type_1,
        R.string.okilo_feedback_type_2,
        R.string.okilo_feedback_type_3,
        R.string.okilo_feedback_type_4,
        R.string.okilo_feedback_type_5,
        R.string.okilo_feedback_type_6)
    private val typeValueList = arrayListOf("HARASSMENT","PAYOUT ISSUE","SCAM","DECLINED","OTHERS","DATA MISUSE")

    private var feedbackPet: OkiloFeedbackPet? = null
    private var uploadPet: OkiloUploadPet? = null
    //反馈类型列表
    private var typeList = arrayListOf<JSONObject>()

    //图片列表
    private var okiloImgAdapter: OkiloFeedbackImageApt? = null

    //图片压缩后存储的临时文件
    private var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    companion object {
        private const val INTENT_KEY_STAR_COUNT = "starCount"
        fun start(context: Context, count: String? = "") {
            val intent = Intent(context, OkiloFeedbackAct::class.java)
            intent.putExtra(INTENT_KEY_STAR_COUNT, count)
            context.startActivity(intent)
        }
    }

    override val pageName: String = "Feedback_Page"

    override fun createOkiloContentView(): View? {
        _binding = OkiloActFeedbackBinding.inflate(layoutInflater)
        return _binding?.root
    }

    @SuppressLint("SetTextI18n")
    override fun initializeOkiloViews() {
        getTitleBarManager()
            .setTitleBarVisibility(View.VISIBLE)
            .setTitle(getString(R.string.okilo_feedback_title))
            .setTitleColor(getColor(R.color.okilo_color_black))
            .setBackButtonIcon(R.mipmap.okilo_root_back_icon)
            .setRightButtonVisibility(View.GONE)
            .setRootBackgroundColor(getColor(R.color.okilo_color_ffeff1f3))
            .setTitleBarColor(getColor(R.color.okilo_color_white))

        initOkiloFeedbackImageListView()
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                OkiloLog.i("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    OkiloLog.i(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        okiloImgAdapter?.let {
                            //最多只能选三张
                            if (it.itemCount == 3){
                                it.removeItem(0)
                            }
                            val imgObj = JSONObject()
                            imgObj.put("isDefault",false)
                            imgObj.put("imgPath",localPath)
                            it.addLastItem(imgObj)

                            onOkiloUploadImageFileAction(localPath)
                        }
                    }
                }

            } else {
                OkiloLog.e("No media selected")
            }
        }
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
        val binding = _binding ?: return
        //输入框监听
        binding.okiloFeedbackRemarkEdit.addTextChangedListener(IRemarkChangeListener)
        binding.okiloFeedbackRemarkEdit.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }

            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_FORM_TRACK.USER_FEEDBACK_REMARK,remark)
            }
        })
        //联系邮箱地址
        binding.okiloFeedbackContactEmailEdit.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }

            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_FORM_TRACK.USER_FEEDBACK_EMAIL,remark)
            }
        })

        //提交
        binding.okiloFeedbackButtonSubmit?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                //问题类型
                if (gOkiloSelectedQuestionTypeItem() == null){
                    showOkiloToast(getString(R.string.okilo_feedback_question_type))
                    return
                }
                val remark = binding.okiloFeedbackRemarkEdit.text.toString()
                if (remark.isEmpty()){
                    showOkiloToast(getString(R.string.okilo_feedback_remark_title))
                    return
                }
                val email = binding.okiloFeedbackContactEmailEdit.text.toString()
                if (email.isEmpty()){
                    showOkiloToast(getString(R.string.okilo_feedback_email_hint))
                    return
                }
                showOkiloLoading(isTouchOut = false, isCancel = true)
                val params = JSONObject().addParams().apply {
                    put("path", OkiloConfigs.gOkiloRequestPath("SUB_FEEDBACK"))
                    put("opinion",remark)//反馈内容
                    put("email",email)//邮箱
                }
                gOkiloSelectedQuestionTypeItem()?.let {
                    params.put("type",it.optString("value"))//反馈类型
                }
                val imgUrls = gOkiloSelectedPicUrls()
                if (imgUrls.isNotEmpty()){
                    params.put("images",imgUrls)
                }
                val starCount = gOkiloStarCount()
                if (starCount.isNotEmpty()){
                    params.put("starNum",starCount)//从评价弹窗进入反馈页,需要传星级数量
                }
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_FEEDBACK_SUBMIT)

                if (feedbackPet == null){
                    feedbackPet = OkiloFeedbackPet(this@OkiloFeedbackAct)
                }
                feedbackPet?.sOkiloFeedbackSubmitRequest(params)
            }
        })
    }

    override fun loadOkiloData() {
        gOkiloLoadQuestionTypeListData()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        okiloImgAdapter?.addFirstItem(imgObj)
    }

    /**
     * 初始化图片列表
     */
    private fun initOkiloFeedbackImageListView() {
        val binding = _binding ?: return
        binding.okiloFeedbackImageListView.setHasFixedSize(false)
        binding.okiloFeedbackImageListView.isNestedScrollingEnabled = false
        binding.okiloFeedbackImageListView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        binding.okiloFeedbackImageListView.layoutManager = layoutManager
        okiloImgAdapter = OkiloFeedbackImageApt(binding.okiloFeedbackImageListView)
        binding.okiloFeedbackImageListView.adapter = okiloImgAdapter
        binding.okiloFeedbackImageListView.itemAnimator = DefaultItemAnimator()
        okiloImgAdapter?.setOnItemChildClickListener(OkiloOnItemChildClickListener { parent, childView, position ->
            okiloImgAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.pictureRemove -> {//删除
                        onOkiloRemoveImgClick(item, position)
                    }

                    R.id.imageAdd -> {//选择图片
                        if (item.optBoolean("isDefault")) {
                            onOkiloPickMediaAction()
                        }
                    }
                }
            }
        })
    }

    /**
     * 删除图片
     */
    private fun onOkiloRemoveImgClick(item: JSONObject, position: Int){
        val adapter = okiloImgAdapter ?: return
        if (item.isNotDefault()) {
            adapter.removeItem(position)
            adapter.ensureDefaultImageExists()
        }
    }

    // 扩展函数
    private fun JSONObject.isNotDefault(): Boolean = !optBoolean("isDefault")

    private fun OkiloFeedbackImageApt.ensureDefaultImageExists() {
        val hasDefaultImage = (0 until itemCount)
            .any { index -> getItem(index).optBoolean("isDefault") }

        if (!hasDefaultImage) {
            val defaultImgObj = JSONObject().apply {
                put("isDefault", true)
            }
            addFirstItem(defaultImgObj)
        }
    }

    private val IRemarkChangeListener = object: TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        @SuppressLint("SetTextI18n")
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
            _binding?.okiloFeedbackRemarkEditLengthText?.text = "$textLength/1000"
        }
    }

    /**
     * 获取意见反馈类型
     */
    private fun gOkiloLoadQuestionTypeListData() {
        typeList.clear()
        typeTitleList.forEachIndexed { index, title ->
            val obj = JSONObject()
            obj.put("title", title)
            obj.put("value", typeValueList[index])
            obj.put("isSelect",false)
            typeList.add(obj)
        }
        sOkiloTypeListView()
    }

    /**
     * 获取选择的问题类型
     */
    private fun gOkiloSelectedQuestionTypeItem(): JSONObject?{
        return typeList.firstOrNull { it.optBoolean("isSelect") }
    }

    /**
     * 获取上传的图片链接
     */
    private fun gOkiloSelectedPicUrls(): String{
        return okiloImgAdapter?.run {
            (0 until itemCount)
                .mapNotNull { index -> getItem(index) }
                .filter { item -> !item.optBoolean("isDefault", false) }
                .joinToString(",") { it.optString("imgUrl", "") }
                .takeIf { it.isNotEmpty() } ?: ""
        } ?: ""
    }

    /**
     * 获取评分数量
     */
    private fun gOkiloStarCount(): String {
        if (intent.extras == null){
            return ""
        }
        return if (intent.extras?.getString(INTENT_KEY_STAR_COUNT) == null) "" else intent.extras?.getString(
            INTENT_KEY_STAR_COUNT
        ).toString()
    }

    /**
     * 设置意见反馈问题类型列表
     */
    private fun sOkiloTypeListView() {
        _binding?.okiloQuestTypeFlexbox?.removeAllViews()
        typeList.forEachIndexed { index, item ->
            createTypeView(item, index).also { view ->
                _binding?.okiloQuestTypeFlexbox?.addView(view)
            }
        }
    }

    private fun createTypeView(item: JSONObject, position: Int) =
        OkiloActFeedbackQuestionTypeItemBinding.inflate(layoutInflater).apply {
            configureTypeView(this, item)
            setupTypeClickListener(this, item, position)
        }.root

    private fun configureTypeView(binding: OkiloActFeedbackQuestionTypeItemBinding, item: JSONObject) {
        with(binding.textType) {
            text = getString(item.optInt("title"))

            if (item.optBoolean("isSelect")) {
                setTextColor(getColor(R.color.okilo_color_white))
                setBackgroundResource(R.drawable.okilo_feedback_question_type_select_bg)
            } else {
                setTextColor(getColor(R.color.okilo_color_ffaaaeaf))
                setBackgroundResource(R.drawable.okilo_white_radius12)
            }
        }
    }

    private fun setupTypeClickListener(binding: OkiloActFeedbackQuestionTypeItemBinding, item: JSONObject, position: Int) {
        binding.textType.setOnClickListener {
            if (item.optBoolean("isSelect")) return@setOnClickListener

            selectTypeItem(position)
            sOkiloTypeListView()
        }
    }

    private fun selectTypeItem(selectedPosition: Int) {
        typeList.forEachIndexed { index, obj ->
            obj.put("isSelect", index == selectedPosition)
            if (index == selectedPosition) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_FEEDBACK_QUESTION_TYPE, getString(obj.optInt("title")))
            }
        }
    }

    /**
     * 图片上传成功，需要删除临时文件
     */
    override fun sOkiloUploadFileSuccess(filePath: String, fileUrl: String) {
        addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_FEEDBACK_UPLOAD_IMAGE,fileUrl)
        val lastItem = okiloImgAdapter?.lastItem as JSONObject
        lastItem.put("imgUrl",fileUrl)

        destinationDirectory?.let {
            if (it.isFile){
                it.delete()
            }
        }
    }

    /**
     * 显示反馈提交成功
     */
    override fun sOkiloFeedbackSubSuccess(msg: String) {
        showOkiloToast(msg)
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },500)
    }

    /**
     * 申请权限
     */
    private fun onOkiloPickMediaAction(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 图片上传
     */
    private fun onOkiloUploadImageFileAction(imgPath: String){
        showOkiloLoading(isTouchOut = false, isCancel = false)
        if (uploadPet == null){
            uploadPet = OkiloUploadPet(this)
        }
        uploadPet?.uploadOkiloFileRequest(imgPath)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}